<template>
  <GlobalContainer className="!bg-[#fff]" :backgroundImage="`${OSS_URL}/images/jiaofei/jiaofei_bg.png`">
    <GlobalHeader :title="pageTitle" showBack :fixed="true" :backgroundImage="`${OSS_URL}/images/jiaofei/jiaofei_bg.png`" />
    <div class="mt-16 min-h-500 rounded-20 bg-white p-32">
      <div class="search-input mb-32" v-if="[0, 1, 2, 3].includes(step)">
        <div class="form-input flex items-center">
          <div class="left-icon">
            <image src="../../static/images/my/search_icon.png" class="mr-20 size-32" />
          </div>
          <input type="text" placeholder="请输入" v-model="searchValue" @change="handleSearch" />
        </div>
      </div>
      <div class="mb-32 ml-12 flex items-center text-28 leading-42 text-[#909399]" v-if="selectedPlot.name">
        <image src="../../static/images/jiaofei/home_icon.png" class="mr-20 size-32" />
        <span>{{ selectedPlot.name }}</span>
        <template v-if="selectedBuilding.name">
          <span class="mx-10">/</span>
          <span>{{ selectedBuilding.name }}</span>
        </template>
        <template v-if="selectedCell.name">
          <span class="mx-10">/</span>
          <span>{{ selectedCell.name }}</span>
        </template>
        <template v-if="selectedRoom.name">
          <span class="mx-10">/</span>
          <span>{{ selectedRoom.name }}</span>
        </template>
      </div>
      <div class="search-input mb-32" v-if="step === 4">
        <div class="form-input flex items-center">
          <div class="left-icon">
            <image src="../../static/images/my/search_icon.png" class="mr-20 size-32" />
          </div>
          <input type="text" placeholder="请输入房屋号" v-model="searchValue" @change="handleSearch" />
        </div>
      </div>
      <div class="list-c pb-100">
        <template v-if="step <= 4">
          <div
            class="item-c flex items-center border-b-1 border-[#E4E7ED]"
            v-for="item in viewList"
            :key="item.name"
            @tap.stop="selectHandle(item, step)"
          >
            <div class="item-title text-30 leading-90 text-[#303133]">{{ item.name }}</div>
            <image src="../../static/images/baoxiu/right_icon.png" class="ml-auto size-32" />
          </div>
          <div v-if="viewList.length === 0" class="empty-container mx-auto mt-240 flex flex-col items-center">
            <div class="empty-img mb-40">
              <image class="h-240 w-330" :src="`${OSS_URL}/images/jiaofei_empty.png`" />
            </div>
            <div class="empty-text text-28 leading-36 text-[#909399]">暂无房屋</div>
          </div>
        </template>
        <div class="form-c" v-else>
          <div class="form-item">
            <div class="label">姓名</div>
            <div class="form-input">
              <wd-input
                v-model="realName"
                placeholder="请输入姓名"
                no-border
                custom-class="custom-class"
                custom-input-class="custom-class"
              />
            </div>
          </div>
          <div class="form-item flex items-center justify-between">
            <template v-for="item in userTypeList" :key="item.id">
              <div
                class="flex h-80 w-156 items-center justify-center rounded-40 border-1 border-[#E4E7ED] text-28 font-normal leading-42 text-[#303133]"
                :class="{ 'bg-[#1E90FF] text-white': selectedUserType === item.value, hasMaster: item.value === 0 && hasMaster }"
                @tap.stop="selectTypeHandle(item)"
              >
                {{ item.name }}
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div class="btn-c px-30 py-20 pb-safe">
      <div class="btn" @tap.stop="nextHandle">下一步</div>
    </div>
  </GlobalContainer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showToast } from '@/utils'
import { getCommunityPage, getRegionPage, getFloorPage, getBuildingRoomPage, checkExistOwner } from '@/common/api/common'
import { submitMemberInfo } from '@/common/api/member'
import { useAccountStore } from '@/store/modules/account'
import { userTypeList } from './config'

const accountStore = useAccountStore()
const OSS_URL = import.meta.env.VITE_OSS_URL
// 小区列表
const plotList = ref<any[]>([])
// 区域地址列表
const smallAddressList = ref<any[]>([])
// 楼栋列表
const buildingList = ref<any[]>([])
// 房屋列表
const cellList = ref<any[]>([])
const roomList = ref<any[]>([])
// 0=业主本人 1=家人(家庭成员) 2=朋友 3=租客

const searchValue = ref('')
const viewList = computed(() => {
  return list.value.filter(item => item.name.includes(searchValue.value))
})

const selectedUserType = ref('')
// 当前列表
const list = ref<any[]>([])

const pageTitle = ref('选择小区')
const step = ref(0)
const selectedPlot = ref<any>({}) // 小区
const selectedSmallAddress = ref<any>({}) // 区域
const selectedBuilding = ref<any>({}) // 楼栋
const selectedCell = ref<any>({}) // 单元
const selectedRoom = ref<any>({}) // 房屋
const realName = ref('')
const selectHandle = (item: any, curStep: number) => {
  switch (curStep) {
    case 0:
      selectedPlot.value = item
      searchValue.value = ''
      step.value++
      getRegionList(item.id).then(res => {
        if (res.length === 0) {
          getBuildingList(selectedPlot.value.id, '')
          step.value++
          pageTitle.value = '选择楼栋'
        } else {
          pageTitle.value = '选择地址'
        }
      })
      break
    case 1:
      selectedSmallAddress.value = item
      list.value = buildingList.value
      pageTitle.value = '选择楼栋'
      searchValue.value = ''
      step.value++
      getBuildingList(selectedPlot.value.id, selectedSmallAddress.value.id || '')
      break
    case 2:
      selectedBuilding.value = item
      pageTitle.value = '选择单元'
      searchValue.value = ''
      step.value++
      createCell(item.totalUnitNum)
      break
    case 3:
      // 选择单元逻辑
      selectedCell.value = item
      pageTitle.value = '选择房屋'
      searchValue.value = ''
      step.value++
      getRoomList(selectedBuilding.value.id)

      break
    case 4:
      selectedRoom.value = item
      // 显示选择用户类型
      // 这个时候检测是否已经有业主
      checkHasMaster()
      step.value++
      break
    case 5:
      selectedUserType.value = item.value
      step.value++
      break
    case 6:
      nextHandle()
      break
    default:
      break
  }
}

// 搜索小区
const handleSearch = () => {
  console.log('搜索小区')
}

// 获取小区
const getCommunityList = () => {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  getCommunityPage({ pageNo: 1, pageSize: 999 })
    .then((res: any) => {
      console.log('[ getCommunityList ] >', res)
      plotList.value = res.records.map((item: any) => ({
        name: item.name,
        id: item.id,
        ...item
      }))
      list.value = plotList.value
    })
    .finally(() => {
      uni.hideLoading()
    })
}

const getRegionList = (communityId: string) => {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  return getRegionPage({ communityId, pageNo: 1, pageSize: 999 })
    .then((res: any) => {
      console.log('[ getRegionList ] >', res)
      if (res.records.length) {
        const cacheList: string[] = []
        res.records.forEach((item: any) => {
          cacheList.push(
            ...handleJson(item.smallAddress || '[]').map((address: any) => ({
              name: address,
              id: address,
              region: item.region
            }))
          )
        })
        smallAddressList.value = cacheList
        console.log('[ smallAddressList ] >', smallAddressList.value)
        list.value = smallAddressList.value
        return smallAddressList.value
      } else {
        return []
      }
    })
    .finally(() => {
      uni.hideLoading()
    })
}

// 处理json
const handleJson = (json: string) => {
  try {
    return JSON.parse(json)
  } catch (error) {
    return []
  }
}

// 获取楼栋
const getBuildingList = (communityId: string, smallAddress: string) => {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  return getFloorPage({ communityId, smallAddress, pageNo: 1, pageSize: 999 })
    .then((res: any) => {
      console.log('[ getBuildingList ] >', res)
      buildingList.value = res.records.map((item: any) => ({
        name: item.name,
        id: item.id,
        ...item
      }))
      list.value = buildingList.value
    })
    .finally(() => {
      uni.hideLoading()
    })
}
// 生成单元
const createCell = (cellNum: number) => {
  cellNum = Number(cellNum)
  cellList.value = Array(cellNum)
    .fill(0)
    .map((_, index) => ({
      name: `${index + 1}单元`,
      id: index + 1
    }))
  list.value = cellList.value
}

// 获取房屋
const getRoomList = (floorId: number) => {
  console.log('[ selectedCell ] >', selectedCell.value)
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  getBuildingRoomPage({ floorId, unitNum: selectedCell.value.id, pageNo: 1, pageSize: 999 })
    .then((res: any) => {
      console.log('[ getRoomList ] >', res)
      roomList.value = res.records.map((item: any) => ({
        name: `${item.roomNum}`,

        id: item.id,
        ...item
      }))
      list.value = roomList.value
    })
    .finally(() => {
      uni.hideLoading()
    })
}
const selectTypeHandle = (item: any) => {
  if (hasMaster.value && item.value === 0) {
    return
  }
  selectedUserType.value = item.value
}

const hasMaster = ref(true)
const checkHasMaster = () => {
  console.log('[ selectedRoom ] >', selectedRoom.value)
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  checkExistOwner(selectedRoom.value.id)
    .then((res: any) => {
      hasMaster.value = res
    })
    .finally(() => {
      uni.hideLoading()
    })
}

onMounted(() => {
  getCommunityList()
})
// 提交接口
const nextHandle = () => {
  console.log('提交接口')
  if (step.value === 0) {
    if (selectedPlot.value.id === '') {
      showToast('请选择小区')
      return
    }
  }
  if (step.value === 1) {
    if (!selectedSmallAddress.value.id) {
      selectHandle({}, 1)
      return
    }
  }
  if (!selectedPlot.value.id) {
    showToast('请选择小区')
    return
  }
  if (!selectedBuilding.value.id) {
    showToast('请选择楼栋')
    return
  }
  if (!selectedCell.value.id) {
    showToast('请选择单元')
    return
  }
  if (!selectedRoom.value.id) {
    showToast('请选择房屋')
    return
  }
  if (!realName.value) {
    showToast('请输入姓名')
    return
  }
  if (selectedUserType.value === '') {
    showToast('请选择用户类型')
    return
  }
  const params = {
    type: selectedUserType.value,
    communityId: selectedPlot.value.id,
    floorId: selectedBuilding.value.id,
    unitNum: selectedCell.value.id,
    smallAddress: selectedSmallAddress.value?.name,
    region: selectedSmallAddress.value?.region,
    roomId: selectedRoom.value.id,
    realName: realName.value
  }
  console.log('[ params ] >', params)
  uni.showLoading({
    title: '提交中',
    mask: true
  })
  submitMemberInfo(params)
    .then((res: any) => {
      if (res) {
        showToast('提交成功，请等待审核')
        uni.navigateBack()
      } else {
        showToast('添加失败')
      }
    })
    .finally(() => {
      uni.hideLoading()
    })
}
</script>

<style scoped lang="scss">
@import '@/styles/common.scss';
.select-plot {
  .select-plot-header {
    padding: 20rpx;
  }
}

.form-input {
  border-radius: 10rpx 10rpx 10rpx 10rpx;
  padding: 20rpx 24rpx;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
}

.form-c {
  .form-item {
    margin-bottom: 30rpx;
    .label {
      font-weight: 400;
      font-size: 30rpx;
      line-height: 46rpx;
      color: #303133;
      margin-bottom: 16rpx;
    }
    .form-input {
      background: #f5f7fa;
      border-radius: 10rpx 10rpx 10rpx 10rpx;
      padding: 20rpx 24rpx;
    }
    .upload-item {
      background: #fafafa;
      border-radius: 8rpx 8rpx 8rpx 8rpx;
      border: 1px solid #dcdfe6;
    }
  }
  :deep(.custom-class) {
    background: #f5f7fa !important;
    font-size: 30rpx;
    color: #303133;
  }
  :deep(.text-area) {
    background: #f5f7fa;
    border-radius: 10rpx 10rpx 10rpx 10rpx;
    border: 1px solid #dcdfe6;
  }
  :deep(.wd-textarea__count) {
    background-color: #f5f7fa;
  }
}
.hasMaster {
  background-color: #efefef !important;
  color: #303133 !important;
  border: 1px solid #e4e7ed !important;
}
</style>
